package com.example.demo.commons.result.common.entity;



import com.example.demo.commons.result.able.ErrorCodeInterface;
import com.example.demo.commons.result.able.ExceptionInterface;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AccessLevel;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Objects;

/**
 * <p> 统一的业务返回包装类 </p>
 *
 * @author tanyunpeng
 * @date 2021/11/18
 */
@Data
@Accessors(chain = true)
@RequiredArgsConstructor(staticName = "of", access = AccessLevel.PRIVATE)
public class BizResult<T> implements java.io.Serializable {

    private static final long serialVersionUID = -6939009336549017035L;
    private static final String SUCCESS = "0";
    private T data;
    private String msg;
    private String code;

    /**
     * 正常返回
     *
     * @param data 数据内容
     * @param <T>  返回数据的类型
     * @return 包装后的返回
     */
    public static <T> BizResult<T> create(T data) {
        return BizResult.<T>of().setCode(SUCCESS).setData(data);
    }

    /**
     * 错误返回
     */
    public static <T> BizResult<T> error(String code, String msg) {
        return BizResult.<T>of().setCode(code).setMsg(msg);
    }

    /**
     * 错误返回
     */
    public static <T> BizResult<T> error(BizResult bizResult) {
        return BizResult.<T>error(bizResult.getCode(), bizResult.getMsg());
    }

    /**
     * 错误返回
     */
    public static <T> BizResult<T> error(ErrorCodeInterface errorCodeEnum) {
        return BizResult.<T>error(errorCodeEnum.getCode(), errorCodeEnum.getDesc());
    }

    /**
     * 错误返回
     */
    public static <T> BizResult<T> error(ErrorCodeInterface errorCodeEnum, String msg) {
        return BizResult.<T>error(errorCodeEnum.getCode(), msg);
    }

    /**
     * 错误返回
     */
    public static <T> BizResult<T> error(ExceptionInterface ex) {
        return BizResult.<T>error(ex.getCode(), ex.getMsg());
    }

    @JsonIgnore
    public Boolean isSuccess() {
        return Objects.equals(SUCCESS, this.code);
    }
}